package com.odontosis.view.cadastro.usuario;

import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.odontosis.entidade.GrupoUsuario;
import com.odontosis.entidade.Usuario;
import com.odontosis.service.UsuarioService;
import com.odontosis.util.StringUtilsOdontosis;
import com.odontosis.view.OdontosisAction;

public class AcaoCadastroUsuarios extends OdontosisAction<UsuarioService> {

	@Override
	public ActionForward execute(ActionMapping arg0, ActionForm form,
			HttpServletRequest arg2, HttpServletResponse arg3) throws Exception {
		FormCadastroUsuarios formulario = (FormCadastroUsuarios) form;
		if(StringUtils.isEmpty(formulario.getMetodo()))
		{
			return onInciar(arg0, form, arg2, arg3);
		}else if(formulario.getMetodo().equals("deletar")){
			return onDeletar(arg0, form, arg2, arg3);
		}else if(formulario.getMetodo().equals("pesquisar")){
			return pesquisar(arg0, form, arg2, arg3);
		}
		return onInciar(arg0, form, arg2, arg3);
	}
	
	public ActionForward pesquisar(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		Usuario usuario = new Usuario();
		Collection<Usuario> usuarios = null;
		FormCadastroUsuarios formulario = (FormCadastroUsuarios) form;
		if(StringUtilsOdontosis.isVazia(formulario.getNome()) && StringUtilsOdontosis.isVazia(formulario.getLogin()) && StringUtilsOdontosis.isVazia(formulario.getGrupo())){
			usuarios = service.findAll();
		}else{
			GrupoUsuario grupo = null;
			try{
				grupo = GrupoUsuario.recuperarPorId(Integer.parseInt(formulario.getGrupo()));
			}catch (Exception e) {
			}
			usuarios = service.pesquisarPorNomeLoginGrupo(formulario.getNome(), formulario.getLogin(), grupo);
		}
		
		request.setAttribute("colecao", usuarios);
		return mapping.getInputForward();
    }

	public ActionForward onInciar(ActionMapping arg0, ActionForm arg1,
			HttpServletRequest request, HttpServletResponse arg3) throws Exception {
	
		UsuarioService servico = new UsuarioService();
		Collection<Usuario> colecao =  servico.findAll();				
			
		request.setAttribute("colecao", colecao);
		return arg0.getInputForward();
	}
	
	public ActionForward onDeletar(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		FormCadastroUsuarios formulario = (FormCadastroUsuarios) form;
		service.excluirLogicamente(service.load(new Long(formulario.getExcluido())));
		formulario.setMetodo(null);
		return pesquisar(mapping, form , request, response);
	}
	

}
